define(function (require, exports, module) {
    'use strict';
    
    var rk = require('rk');
    
    var FancyMap = require('fancymap');
    var rk_userService = require('core/services/2.0/rk_userService');

    $.widget('rk.wrStatisticsCtrl', {
        options: {
            startMom: null,
            endMom: null,
            titleSelector: '>span[class="title"]',
            entitySelector: 'ul.entity_data',
            totalSelector: 'ul.total',

            dataContainerSel: '.detail_sales_tabpage',

            belongTypeId: window.editorBelongTypeId,
            currencyUnit: rk.i18n('WORKREPORT_UNIT_YUAN')
        },
        _create: function () {
            var me = this;
            var elem = me.element;
        },
        _init: function () {
            var me = this;
            var elem = me.element;
            var con = elem.find(me.options.dataContainerSel);
            elem.on('click', 'li[sttstsNum="true"]', function () {
                var li = $(this);
                var num = li.find('span[key]');
                var key = num.attr('key');
                var val = num.attr('val');

                var popup = true;
                if (!val || val == '0') popup = false;
                if (parseInt(val) == 0) popup = false;
                if (!popup) {
                    //num.effect( 'shake',  { distance: 10, times: 2 }, 400 );
                    return;
                }
                workreportService.popupStatistics(key, me.currentTypeAlias, me.options.belongTypeId, me.currentOwnerId, me.currentStart, me.currentEnd);
            });
            var contentCon = con.find('.tab_content');
            con.on('click', 'li[isTabBtn="true"]', function () {
                con.find('.tab_nav').find('li').removeClass('hover');
                var tabBtn = $(this);
                tabBtn.addClass('hover');
                var gid = tabBtn.attr('gid');
                con.find('div[class="sales_content"][gid]').hide();
                con.find('div[class="sales_content"][gid="' + gid + '"]').show();
            });
        },
        updateTitle: function (type, start, end) {
            var me = this;
            var elem = me.element;
            var span = elem.find(me.options.titleSelector);
            if (span.size() == 0) return;
            switch (type) {
                case 'day':
                    span.html(rk.i18n('WORKREPORT_STATISTICS_THIS_DAY'));
                    break;
                case 'week':
                    span.html(rk.i18n('WORKREPORT_STATISTICS_THIS_WEEK'));
                    break;
                case 'month':
                    span.html(rk.i18n('WORKREPORT_STATISTICS_THIS_MONTH'));
                    break;
                default:
            }
        },
        updateTitle2: function (type, start, end) {
            var me = this;
            var elem = me.element;
            var span = elem.find(me.options.titleSelector);
            if (span.size() == 0) return;
            switch (type) {
                case 'day':
                    span.html((start.month() + 1) + rk.i18n('WORKREPORT_MONTH') + start.date() + rk.i18n('WORKREPORT_DAY'));
                    break;
                case 'week':
                    end.subtract(12, 'hours');
                    span.html((start.month() + 1) + rk.i18n('WORKREPORT_MONTH') + start.date() + rk.i18n('WORKREPORT_DAY') + ' - ' + (end.month() + 1) + rk.i18n('WORKREPORT_MONTH') + end.date() + rk.i18n('WORKREPORT_DAY'));
                    break;
                case 'month':
                    span.html((start.month() + 1) + rk.i18n('WORKREPORT_MONTH'));
                    break;
                default:
            }
        },
        _cacheDict: function (params) {
            var me = this;
            for (var i = 0, len = params.length; i < len; i++) {
                var pm = params[i];
                workreportService.updateStatisticsInfo(pm.id, {
                    title: pm.parameterName
                });
            }
        },
        currentTypeAlias: null,
        currentOwnerId: null,
        currentOwnerName: null,
        currentStart: -1,
        currentEnd: -1,
        loadData: function (typeAlias, ownerId, start) {
            var me = this;
            var elem = me.element;
            me.currentOwnerId = ownerId;
            me.currentOwnerName = rk_userService.getUserInfo(ownerId).name;
            me.currentTypeAlias = typeAlias;
            start.hour(0);
            start.minutes(0);
            start.seconds(0);
            var end = moment(start);
            end.add(1, typeAlias);
            me.beLoading(true);
            me.updateTitle(typeAlias, start, end);
            var url = '/json/oa_workreport/list-reports.action';
            $.ajax({
                url: url,
                data: {
                    //belongId: getBelongId()
                    belongTypeId: me.options.belongTypeId,
                    pageUserId: ownerId,
                    startTime: start.unix() * 1000,
                    endTime: end.unix() * 1000
                },
                dataType: 'json',
                type: 'POST'
            }).success(function (data) {
                me.beLoading(false);
                if (data && data.data && data.data.salesParameters) {
                    me._cacheDict(data.data.salesParameters);
                }
                if (data && data.data && data.data.activityRecords) {
                    var records = data.data.activityRecords;
                    me.bindData(records);
                    if (records.length == 0) {
                        me.beNodata(true); //nodata.show();
                    }
                    me.currentStart = start;
                    me.currentEnd = end;
                } else {
                    me.beNodata(true); //nodata.show();
                }
            }).error(function () {
                me.beNodata(true); //nodata.show();
            }).complete(function () {
                //
            });
        },
        _filterData: function (oldarr) {
            var newarr = [];
            for (var i = 0; i < oldarr.length; i++) {
                var r = oldarr[i];
                var key = r.key + '';
                if (key != '-1' && key != '-2') newarr.push(r);
            }
            //-4需要显示在-3之前
            //-7显示在最前
            var idxOf_7;
            var idxOf_3;
            var idxOf_4;
            for (var i = 0; i < newarr.length; i++) {
                var r = newarr[i];
                var key = r.key + '';
                if (key == '-3') idxOf_3 = i;
                if (key == '-4') idxOf_4 = i;
                if (key == '-7') idxOf_7 = i;
            }
            if (idxOf_3 != null && idxOf_4 != null) {
                var cache = newarr[idxOf_3];
                newarr[idxOf_3] = newarr[idxOf_4];
                newarr[idxOf_4] = cache;
            }
            if (idxOf_7 != null && idxOf_7 != 0) {
                var cache = newarr[idxOf_7];
                newarr[idxOf_7] = newarr[0];
                newarr[0] = cache;
            }
            return newarr;
        },
        bindData: function (comingRecords) {
            var me = this;
            var elem = me.element;
            var con = elem.find(me.options.dataContainerSel);
            var records = me._filterData(comingRecords); //滤掉-1和-2
            var groupinfo = workreportService.groupInfo;
            var groupmap = workreportService.groupMap;
            var renderMap = new FancyMap();
            for (var i = 0; i < groupinfo.length; i++) {
                var ginfo = groupinfo[i];
                renderMap.put(ginfo.id, []);
            }
            var arr = [];
            for (var i = 0; i < records.length; i++) {
                var r = records[i];
                var key = r.key;
                var sysinfo = workreportService.StatisticsInfo[key + ''];
                r.theme = sysinfo.theme;
                var groupId = sysinfo.groupId;
                 arr = renderMap.get(groupId);
                //if (arr.length < 3) //业务要求，每组最多显示3条，后记：应最新业务要求，不再有3个的限制
                arr.push(r);
            }
            if (arr.length == 0) {
                me.hide();
                return;
            }
            //如果group中无数据，则不显示
            var nodisplayGid = [];
            renderMap.each(function (key, arr) {
                if (arr.length == 0) nodisplayGid.push(key);
            });
            for (var i = 0, len = nodisplayGid.length; i < len; i++) {
                renderMap.remove(nodisplayGid[i]);
            }
            //生成tab头
            var totalTabHtml = '<ul class="tab_nav">';
            var count = 0;
            renderMap.each(function (key, arr) {
                totalTabHtml = totalTabHtml + '<li isTabBtn="true" class="' + (count == 0 ? 'hover' : '') + '" gid="' + key + '">' + '<a href="javascript:;">' + groupmap[key].title + '</a>' + '</li>';
                count++;
            });
            totalTabHtml = totalTabHtml + '</ul>' + '<div class="tab_content">';
            //生成tab内容
            var count = 0;
            renderMap.each(function (key, arr) {
                totalTabHtml = totalTabHtml + '<div class="sales_content" ' + (count != 0 ? 'style="display:none;"' : '') + ' gid="' + key + '">' + '<ul class="total">';
                for (var i = 0, len = arr.length; i < len; i++) {
                    var item = arr[i];
                    var value = numeral(item.value).value();
                    var text = (item.theme == 'currency' ? numeral(item.value).format('0,0') : value);
                    totalTabHtml = totalTabHtml + '<li sttstsNum="true" class="' + (i == arr.length - 1 ? 'last' : '') + '">' + '<a href="javascript:;" title="' + rk.i18n('WORKREPORT_DETAIL_CLICK') + '">' + '<span>' + workreportService.getStatisticsTitle(item.key) + (item.theme == 'currency' ? '（' + me.options.currencyUnit + '）' : '') + '</span>' + '<span href="javascript:;" title="' + rk.i18n('WORKREPORT_DETAIL_CLICK') + '" class="' + (item.theme ? item.theme : 'num') + ' ' + (value == 0 ? '' : '') + '" key="' + item.key + '" val="' + value + '">' + text + '</span>' + '</a>' + '</li>';
                }
                totalTabHtml = totalTabHtml + '</ul></div>';
                count++;
            });
            totalTabHtml = totalTabHtml + '</div>';
            con.html(totalTabHtml);
        },
        beNodata: function (bool) {
            var me = this;
            me.hide();
            return;
            var elem = me.element;
            var con = elem.find(me.options.dataContainerSel);
            if (bool) {
                con.html('<span class="nodata" style="display:none;">' + rk.i18n('WORKREPORT_NO_DATA') + '</span>');
            } else {
                con.find('span[class="nodata"]').remove();
            }
        },
        beLoading: function (bool) {
            var me = this;
            var elem = me.element;
            var con = elem.find(me.options.dataContainerSel);
            if (bool) {
                con.html('<span class="loading">' + rk.i18n('WORKREPORT_SALES_DATA_LOADING') + '</span>');
            } else {
                con.find('span[class="loading"]').remove();
            }
        },
        hide: function () {
            var me = this;
            var elem = me.element;
            var span = elem.find(me.options.titleSelector);
            elem.hide();
            span.hide();
        }

    });

});
